package com.lg.my.netty.codec;

import com.lg.consts.NettyConst;
import com.lg.netty.codec.User;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 研究 编解码 客户端
 *
 * @author by Mr. Li 2021/4/22 2:26
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    final ChannelPipeline pipeline = socketChannel.pipeline();
                    //pipeline.addLast(new StringEncoder());
                    //pipeline.addLast(new ObjectEncoder());
                    pipeline.addLast(new ObjectEncodeByProtocl());

                    pipeline.addLast(new NettyClientHandler());
                }
            });

            final ChannelFuture channelFuture = bootstrap.connect(NettyConst.ADDRESS_IP, NettyConst.ADDRESS_PORT).sync();
            Scanner scanner = new Scanner(System.in);

            //while (scanner.hasNextLine()) {
            //    channelFuture.channel().writeAndFlush(scanner.nextLine());
            //}
            //final User user = new User();
            //user.setId(1);
            //user.setName("xiaogang");
            //channelFuture.channel().writeAndFlush(user);
            channelFuture.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully();
        }
    }
}
